/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Principal.java
 *
 * Created on 05/09/2011, 20:22:35
 */

package br.com.fiap.sir;
import br.com.fiap.sir.api.Operacoes;
import br.com.fiap.sir.api.Grafos;
import br.com.fiap.sir.beans.Node;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set; 
import javax.swing.JOptionPane;

/**
 *
 * @author rm61825
 */
public class Principal extends javax.swing.JFrame {
    public Operacoes op;
    public File[] arquivos;
    public HashMap<String,Node> grafos = new HashMap<String,Node>();
    String sequence = "", auxsequence = "";
    public HashMap<Integer,ArrayList<String>> fila = new HashMap<Integer,ArrayList<String>>();

    /** Creates new form Principal */
    public Principal() {
        initComponents();
        op = new Operacoes();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtLog = new javax.swing.JTextPane();
        jLabel1 = new javax.swing.JLabel();
        txtPath = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        btnListar = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        btnArt = new javax.swing.JButton();
        btnLer = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        btnNiveis = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Log"));

        txtLog.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtLogKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(txtLog);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 671, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE)
                .addContainerGap())
        );

        jLabel1.setText("Caminho dos arquivos:");

        txtPath.setText("C:\\Arquivos");
        txtPath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPathActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Exercicios 1 e 2"));

        btnListar.setText("Listar Contatos");
        btnListar.setEnabled(false);
        btnListar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnListarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addComponent(btnListar)
                .addContainerGap(30, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(btnListar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Exercicio 3"));

        btnArt.setText("Verifica Articulaçoes");
        btnArt.setEnabled(false);
        btnArt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnArtActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(18, Short.MAX_VALUE)
                .addComponent(btnArt)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(btnArt)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnLer.setText("Ler Arquivos");
        btnLer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLerActionPerformed(evt);
            }
        });

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Exercicio 4"));

        btnNiveis.setText("Busca em níveis");
        btnNiveis.setEnabled(false);
        btnNiveis.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNiveisActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnNiveis)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addComponent(btnNiveis)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(4, 4, 4)
                                .addComponent(txtPath, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btnLer))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(21, 21, 21)
                                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(29, 29, 29)
                                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel1))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnLer)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnLerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLerActionPerformed
        try{
            this.arquivos = op.lerDiretorio(txtPath.getText());
            
             StringBuilder log = new StringBuilder();
            if(this.arquivos == null || this.arquivos.length == 0){
                txtLog.setText("Não existem arquivos no diretorio.");
            }
            for(File f:arquivos){

                log.append("Lendo o arquivo: ");
                log.append(f.getName());
                log.append(" ... ");

                String conteudo = op.lerArquivo(f);
                String[] ligacoes;

                conteudo = conteudo.toLowerCase();
                conteudo = conteudo.trim();
                conteudo = conteudo.replaceAll("[a-z]", "");
                conteudo = conteudo.replace(" ","");

                //Faz o parse de todas as formas possíveis...
                ligacoes = conteudo.split(",");
                if(ligacoes.length == 1 ){
                    ligacoes = conteudo.split("\n");
                    if(ligacoes.length == 1 ){
                        ligacoes = conteudo.split("\t");
                    }
                }

                //Gera a key
                String key = f.getName().toLowerCase().replaceAll("[a-z]","").replace(".","").trim();
                            //Gera o grafo...
                Node n = new Node();
                n.setRm(key);
                n.setLigacoes(ligacoes);
                n.setVisitado(false);
                grafos.put(key, n);

                log.append("OK! Nº Ligações: ");
                log.append(ligacoes.length);
                log.append("\n");

            }
            txtLog.setText(txtLog.getText() + log.toString());
            btnListar.setEnabled(true);
            btnArt.setEnabled(true);
            btnNiveis.setEnabled(true);

        }catch (Exception ex){
            txtLog.setText("Não existem arquivos no diretorio.");
        }



}//GEN-LAST:event_btnLerActionPerformed

    private void btnListarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnListarActionPerformed
        txtLog.setText("");
        String rm = JOptionPane.showInputDialog("Digite o seu RM:");
        try{
            if(grafos.containsKey(rm)){
                geraGrafo(rm);

                txtLog.setText(txtLog.getText() + "\nAlunos que o RM " + rm + " não consegue contactar: \n\n");

                Iterator it = grafos.entrySet().iterator();

                while(it.hasNext()){
                    Map.Entry entry = (Map.Entry)it.next();
                    String key = (String)entry.getKey();
                    if(grafos.get(key).isVisitado()==false){
                        txtLog.setText(txtLog.getText() + key + "\n\n");
                    }
                }
            }
            else{
                JOptionPane.showMessageDialog(null, "Não foi encontrado o RM escolhido");
            }
        }
        catch(NullPointerException ex){
            JOptionPane.showMessageDialog(null, "Não foi encontrado o RM escolhido");
            return;
        }

        grafos = Grafos.limpaFlags(grafos);
    }//GEN-LAST:event_btnListarActionPerformed

    private void btnArtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnArtActionPerformed

        try{
            StringBuilder log = new StringBuilder();
            String rmInput = JOptionPane.showInputDialog("Digite o RM para buscar a articulação");
            Grafos g = new Grafos();
            g.setMatriz(grafos);
            g.buscaArt(grafos.get(rmInput));
            grafos = g.getMatriz();

            log.append("Articulações: \n");
            Set<String> keys = grafos.keySet();
            for(String key : keys){
                Node atual = grafos.get(key);
                if(atual.isArticulacao()){
                    log.append(" -");
                    log.append(atual.getRm());
                    log.append("\n");
                }
            }

            txtLog.setText(log.toString());
        }catch(NullPointerException ex){
            JOptionPane.showMessageDialog(null, "RM não encontrado");
        }

        grafos = Grafos.limpaFlags(grafos);
    }//GEN-LAST:event_btnArtActionPerformed

    private void txtPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPathActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtPathActionPerformed

    private void btnNiveisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNiveisActionPerformed

        fila = new HashMap<Integer,ArrayList<String>>();

        String rmInput = JOptionPane.showInputDialog("Digite o RM para buscar as conexões por Nível");
        txtLog.setText("");
        try{
            if(grafos.containsKey(rmInput)){
                buscaNiveis(rmInput, 0);

                Set<Integer> nodes = fila.keySet();
                for (Iterator<Integer> it = nodes.iterator(); it.hasNext();)
                {
                    Integer node = it.next();
                    txtLog.setText(txtLog.getText() + "Nível: " + node + " - Total: " + fila.get(node).size() +
                                   " - Nós: " + fila.get(node) + "\n");
                }     


            }
        }
        catch(NullPointerException ex){
            JOptionPane.showMessageDialog(null, "Não foi encontrado o RM escolhido");
            return;
        }

        grafos = Grafos.limpaFlags(grafos);
    }//GEN-LAST:event_btnNiveisActionPerformed

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        
    }//GEN-LAST:event_formKeyPressed

    private void txtLogKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtLogKeyPressed
        if(evt.getKeyCode() == 120){
            JOptionPane.showMessageDialog(null, "Feito por Eduardo, Felipe e Wagner - 3º SIR","Anti-copia",JOptionPane.INFORMATION_MESSAGE);
        };
    }//GEN-LAST:event_txtLogKeyPressed
    private void buscaNiveis(String rm, int nivel){
        try{
            ArrayList<String> t = new ArrayList<String>();
            Node n = grafos.get(rm);
            if (n.getLigacoes().length>0){
                n.setVisitado(true);
                nivel++;
                String[] ligacoes = n.getLigacoes();
                for(String i:ligacoes){
                    n = grafos.get(i);
                    if(!n.isVisitado()){
                         n.setVisitado(true);
                         t.add(i);
                         
                     }
                }
                if(t.size()>0)
                {
                    //Faz o merge das listas caso já exista alguma coisa no nivel
                    ArrayList<String> tmp = fila.get(nivel);
                    if(tmp != null && tmp.size()>0){
                        t.addAll(tmp);
                    }

                    fila.put(nivel, t);
                    for(String i:t){
                        buscaNiveis(i,nivel);
                    }
                }
            }
        }
        catch(NullPointerException ex){
            JOptionPane.showMessageDialog(null, "o RM " + rm + " não foi encontrado");
        }
    }

    private void geraGrafo(String rm){
        
        try{
            Node n = grafos.get(rm);
            String[] ligacoes = n.getLigacoes();
            if(!n.isVisitado()){
                sequence=sequence + rm + " ";
                for(String i:ligacoes){
                    n.setVisitado(true);
                    geraGrafo(i);
                }
                if(sequence.length()>=auxsequence.length())
                    txtLog.setText(txtLog.getText() + sequence + "\n\n");

                auxsequence=sequence;

                sequence = sequence.substring(0, sequence.length()-(rm.length()+1));
            }
        }catch(NullPointerException ex){
            JOptionPane.showMessageDialog(null, "o RM " + rm + " não foi encontrado");
        }
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnArt;
    private javax.swing.JButton btnLer;
    private javax.swing.JButton btnListar;
    private javax.swing.JButton btnNiveis;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane txtLog;
    private javax.swing.JTextField txtPath;
    // End of variables declaration//GEN-END:variables

}
